/**
 * Created by moc on 2016/4/20.
 */
var fs = require('fs')
var events = require("events");
var Store= require('express-session').Store
var util = require('util')

function FileStore() {
    Store.call(this);
}
util.inherits(FileStore, Store)
module.exports=FileStore
var config = {
    path: "./sessions"
}

var init = function () {
    if (!fs.existsSync(config.path)) {
        fs.mkdirSync(config.path)
    }
}
init()

FileStore.prototype.destory = function (sid, callback) {
    fs.unlink(config.path + "/" + sid,function(){
        console.log("delete session "+sid)
        callback(0)
    })
}

FileStore.prototype.get = function (sid, callback) {
    fs.readFile(config.path + "/" + sid,{},function(err,data){
        var se={}
        if(!err)
        {
            se=JSON.parse(data)
            console.log("get session "+sid)
        }
        callback(err,se)
    })
}

FileStore.prototype.set = function (sid, session, callback) {
    var str = JSON.stringify(session)
    fs.writeFile(config.path + "/" + sid, str, {}, function (err) {
        console.log("set session "+sid)
        callback(err)
    })
}


